require 'middleclass'
require 'Display'
require 'MathUtils'

Bug = class('Bug', Display)

function Bug:initialize(imageSheet, sheet, planet, radius)
    if(radius == nil)then
        radius = 10
    end
    local disObj = display.newImageRect(imageSheet,sheet ,radius * 2,radius * 2)
    disObj:setFillColor(80, 80, 80 ) 
    local pos = planet:getVector()
    disObj.x = planet.body.x
    -- el bug se introduce un poco en el planeta
    disObj.y = planet.body.y + radius - 5 + planet.radio
    physics.addBody( disObj, "static", { density = 1, friction = 0.0, bounce = 0.9, radio = radius})
    Display.initialize(self, disObj) 
    
    self.planet = planet
    self.direction = MathUtils.LEFT
    self.angularIncrement = -1.5/self.planet.radio
    
    --update listener
    Runtime:addEventListener("enterFrame", self)
    Runtime:addEventListener("clean", self)
    
    --evitar que todos sean creados en el mismo sitio (cutre)
    self:setVector(MathUtils.rotate( self.planet.body, self:getVector(), math.random(180))) 
end

function Bug:enterFrame()
    if(player.planet ~= nil and player.planet == self.planet)then
        if(player.direction ~= self.direction)then
            self.direction = player.direction
            self.body:scale(-1,1)
            self.angularIncrement = -self.angularIncrement
        end
    end
    
    self:setVector(MathUtils.rotate( self.planet.body, self:getVector(), self.angularIncrement)) 
    self.body.rotation = MathUtils.angleBetween ( self.planet:getVector(), self:getVector() )

end

function Bug:clean()
    print('cleanBug')
    Runtime:removeEventListener("enterFrame", self)
    Runtime:removeEventListener("clean", self)
end



